package com.example.project.service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Collectors;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.alibaba.fastjson2.JSONObject;
import com.example.message.entity.Message;
import com.example.message.service.MessageService;
import com.example.project.entity.Issue;
import com.example.project.entity.User;
import com.example.project.mapper.IssueMapper;
import com.example.project.service.impl.BaseServiceImpl;
import com.example.project.utils.DateUtils;
import com.example.project.utils.ThreadPoolUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 服务实现基类
 * 
 * @param <M> Mapper类型
 * @param <T> 实体类型
 */
@Service
public class IndexService extends BaseServiceImpl {

	@Autowired
	private ProjectService projectService;

	@Autowired
	private IssueService issueService;

	@Autowired
	private IssueMapper issueMapper;

	@Autowired
	private MessageService messageService;

	public void getMain(ModelMap mmap, Long userId) {
		// TODO Auto-generated method stub

		User user = getUser();
		mmap.put("user", user);

		ThreadPoolTaskExecutor executor = ThreadPoolUtils.createDefaultThreadPool("example-pool-system-index");

		// 查询基础数据
		Callable<Map<String, Long>> indexCallable = new Callable<Map<String, Long>>() {
			public Map<String, Long> call() throws Exception {
				Map<String, Long> map = new HashMap<String, Long>();
				// 当日需求量
				long issueTodayTotal = issueService.getTodayCount();
				map.put("issueTodayTotal", issueTodayTotal);
				// 总需求量
				long issueTotal = issueService.getCount(null);
				map.put("issueTotal", issueTotal);
				// 客户数量
				long projectTotal = projectService.getCountByState(1);
				map.put("projectTotal", projectTotal);
				List<Integer> pendingStatus = Lists.newArrayList();
				pendingStatus.add(1);
				pendingStatus.add(7);
				// 待处理需求
				List<Map<String, Object>> issueStatusList = issueService.selectIssueStatusTotal();
				long pendingTotal = issueStatusList.stream()
						.filter(info -> pendingStatus.contains(info.get("status_id")))
						.mapToLong(info -> Long.parseLong(String.valueOf(info.get("issue_count")))).sum();
				map.put("pendingTotal", pendingTotal);

				// 待分配需求
				long unassignedTotal = issueMapper.selectTotalByUnassigned();
				map.put("unassignedTotal", unassignedTotal);
				return map;
			}
		};

		// 查询基础数据
		Callable<Map<String, String>> issueChartCallable = new Callable<Map<String, String>>() {
			public Map<String, String> call() throws Exception {
				Map<String, String> map = new HashMap<String, String>();
				ObjectMapper objectMapper = new ObjectMapper();
				// 查询每月需求量
				List<Map<String, Object>> issueList = issueService.findListGroupByMonth();
				List<String> monthList = issueList.stream().map(info -> String.valueOf(info.get("month")) + "月")
						.toList();
				map.put("monthList", objectMapper.writeValueAsString(monthList));
				List<String> totalList = issueList.stream().map(info -> String.valueOf(info.get("total"))).toList();
				map.put("totalList", objectMapper.writeValueAsString(totalList));
				return map;
			}
		};

		// 客户需求分布
		Callable<Map<String, String>> projectCallable = new Callable<Map<String, String>>() {
			public Map<String, String> call() throws Exception {
				Map<String, String> map = new HashMap<String, String>();
				ObjectMapper objectMapper = new ObjectMapper();

				// 查询所有项目
				List<Map<String, Object>> issueList = issueService.findTotalGroupByProjectId();
				List<String> projectNameList = issueList.stream().map(info -> String.valueOf(info.get("project_name")))
						.toList();
//				List<String> identifierList = issueList.stream().map(info->String.valueOf(info.get("identifier"))).toList();
				List<String> issueTotalList = issueList.stream().map(info -> String.valueOf(info.get("issue_count")))
						.toList();

				// 在后端生成颜色数组
				List<String> colorList = generateColors(issueList.size());

				// 将列表转换为JSON字符串，确保字符串有双引号
				map.put("projectNameList", objectMapper.writeValueAsString(projectNameList));
				map.put("identifierList", objectMapper.writeValueAsString(colorList));
				map.put("issueTotalList", objectMapper.writeValueAsString(issueTotalList));
				map.put("colorList", objectMapper.writeValueAsString(colorList));
				return map;
			}
		};
		// 我的消息
		Callable<List<Message>> messageCallable = new Callable<List<Message>>() {
			public List<Message> call() throws Exception {

				List<Message> userMessageList = messageService.findListByReceiverId(userId, null, null, 10);

				// 为每个消息设置显示颜色
				if (userMessageList != null && !userMessageList.isEmpty()) {
					String[] colorPalette = { "#4361ee", "#4cc9f0", "#f72585", "#6c757d" };
					for (int i = 0; i < userMessageList.size(); i++) {
						Message message = userMessageList.get(i);
						message.setDisplayColor(colorPalette[i % colorPalette.length]);
					}
				}

				return userMessageList;
			}
		};

		// 我的任务
		Callable<List<Issue>> issueCallable = new Callable<List<Issue>>() {
			public List<Issue> call() throws Exception {
				Issue issue = new Issue();
				issue.setAssignedToId(userId);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("dataScope", "order by update_time desc");
				issue.setParams(params);
				// 直接查询10条数据，提高效率
				List<Issue> issueList = issueService.findListByConditionWithLimit(issue, 10);
				return issueList;
			}
		};

		// 日历
		Callable<Map<String, Object>> calendarCallable = new Callable<Map<String, Object>>() {
			public Map<String, Object> call() throws Exception {
				Map<String, Object> map = new HashMap<>();

				// 获取当前日期
				LocalDate today = LocalDate.now();

				// 获取当前是这一年的第几周（ISO标准，周一为一周的开始）
				int weekOfYear = today.get(WeekFields.of(Locale.CHINA).weekOfWeekBasedYear());
				map.put("weekOfYear", weekOfYear);

				// 获取这周的周一到周日日期列表
				LocalDate monday = today.with(DayOfWeek.MONDAY);
				List<String> weekDates = new ArrayList<>();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d");

				// 生成周一到周日的日期
				for (int i = 0; i < 7; i++) {
					LocalDate date = monday.plusDays(i);
					weekDates.add(date.format(formatter));
				}

				map.put("weekDates", weekDates);

				// 获取周一和周日日期并赋值给Issue对象
				LocalDate sunday = monday.plusDays(6);

				DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String sDate = monday.format(dateFormatter);
				String eDate = sunday.format(dateFormatter);

				Issue issue = new Issue();
				if (!user.isAdmin()) {
					issue.setAssignedToId(user.getUserId());
				}
				issue.setsDate(sDate);
				issue.seteDate(eDate);
				List<Issue> issues = issueService.findListByCondition(issue);

				// 按createTime的日期分组，key为日期的"d"格式
				Map<String, List<Issue>> issuesByDate = issues.stream().filter(item -> item.getCreateTime() != null)
						.collect(Collectors.groupingBy(item -> item.getCreateTime().format(formatter)));

				map.put("issuesByDate", issuesByDate);

				return map;
			}
		};

		try {
			CompletableFuture<Map<String, Long>> indexAsync = ThreadPoolUtils.submitAsync(executor, indexCallable);
			mmap.put("index", indexAsync.get());

			CompletableFuture<Map<String, String>> issueChartAsync = ThreadPoolUtils.submitAsync(executor,
					issueChartCallable);
			mmap.put("issue", issueChartAsync.get());

			CompletableFuture<Map<String, String>> projectAsync = ThreadPoolUtils.submitAsync(executor,
					projectCallable);
			mmap.put("project", projectAsync.get());

			// 消息
			CompletableFuture<List<Message>> messageAsync = ThreadPoolUtils.submitAsync(executor, messageCallable);
			mmap.put("userMessageList", messageAsync.get());

			// 我的任务
			CompletableFuture<List<Issue>> issueAsync = ThreadPoolUtils.submitAsync(executor, issueCallable);
			mmap.put("userIssueList", issueAsync.get());

			// 关注的任务

			// 日历
			CompletableFuture<Map<String, Object>> calendarAsync = ThreadPoolUtils.submitAsync(executor,
					calendarCallable);
			mmap.put("calendar", calendarAsync.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成遵循四色原则的颜色数组
	 * 
	 * @param count 需要生成的颜色数量
	 * @return 颜色数组（遵循四色原则）
	 */
	private List<String> generateColors(int count) {
		List<String> colors = new ArrayList<>();
		String[] colorPalette = { "#4361ee", "#4cc9f0", "#f72585", "#6c757d" };

		// 遵循四色原则：循环使用四种颜色，确保相邻区域颜色不同
		for (int i = 0; i < count; i++) {
			colors.add(colorPalette[i % colorPalette.length]);
		}

		return colors;
	}

}